import React, { useEffect, useRef, useState } from 'react';
import { useSetState } from 'ahooks';
import { connect } from 'umi';
import { TRDefault } from '@/components/index.js';
import { HttpCode } from '#/utils/contacts.js';
import { Calender, List, SearchFrom } from './components';
import { GET_MONTH_VIEW_PARAMS, TABS_LIST } from './dictionary';
import { dealMarketOptions, getCreatorResultData, getDate, getDealElementOptions } from './tool';
import {
  getMarket,
  getMaxElectricityGenerationRole,
  getMonthViewH,
  getTodoNoticeSequenceListH,
  pendingCreatorH,
} from './service';
import type {
  ICalenderOption,
  ICompontentsIsLoading,
  IDealElementOptions,
  IInitialValues,
  IMarketOptions,
  IOriginCreatorOption,
  IProps,
  ISearchCriteriaData,
  ISearchFormData,
} from './type';
import styles from './index.less';
import moment from 'moment/moment';
import _ from 'lodash';
import { useTRState } from '#/utils/trHooks';

const DealCalenderRedesign = (props: IProps) => {
  const { buttonPermissions } = props;
  const [error, setError] = useState<string>('');
  const [searchFormData, setSearchFormData] = useTRState<ISearchFormData>({
    marketOptions: [],
    dealElementOptions: [],
    dealElementModalOptions: [],
    originDealElementOptions: [],
    dealElementDataObj: {},
    creatorOptions: [],
    creatorOptionsObj: {},
    originCreatorOptions: {},
    groupOptions: [],
    groupOptionsObj: {},
  });
  const [initialValues, setInitialValues] = useTRState<any>({});
  const [activeKey, setActiveKey] = useState<TABS_LIST>(TABS_LIST.TODO_TABS_TYPE);
  const [monthData, setMonthData] = useState<ICalenderOption>({});
  const [listData, setListData] = useState<Record<string, any>[]>([]);
  const [flashKey, setFlashKey] = useState<string | number>('');
  const [monthflashKey, setMonthflashKey] = useState<string>('');
  const [listIsError, setListIsError] = useState<boolean>(false);
  const [selectFlashKey, setSelectFlashKey] = useState<number>();
  const [checkedFlashKey, setCheckedFlashKey] = useState<number>();
  const [monthViewParams, setMonthViewParams] = useState<{ beginDate: string; endDate: string }>(
    GET_MONTH_VIEW_PARAMS,
  );
  const [checkedDate, setCheckedDate] = useState<string>(moment().format('YYYY-MM-DD'));
  const [searchCriteriaData, setSearchCriteriaData] = useSetState<ISearchCriteriaData>({
    dateList: [],
    marketList: [],
    queryType: TABS_LIST.TODO_TABS_TYPE,
    keyWords: '',
    stationList: [],
    userList: [],
    refreshUL: '',
  });
  const [componentsLoadingStatus, setComponentsLoadingStatus] = useSetState<ICompontentsIsLoading>({
    calenderIsLoading: true,
    listIsLoading: true,
  });
  const isInit = useRef(true);

  useEffect(() => {
    const obj = getDate(checkedDate);
    pendingCreatorH(obj.dateList, activeKey).then((res) => {
      if (res?.statusCode === HttpCode.SUCCESS) {
        const _creatorData: any = res?.data || {};
        // 用户列表首位添加系统用户
        _creatorData.userList = _creatorData?.userList || [];
        _creatorData?.userList?.unshift({ name: '系统', userId: -1 });
        const creatorResultData = getCreatorResultData(_creatorData);
        const data = {
          creatorOptions: creatorResultData.creatorOptions || [],
          creatorOptionsObj: creatorResultData.creatorOptionsObj || {},
          groupOptions: creatorResultData.groupOptions || [],
          groupOptionsObj: creatorResultData.groupOptionsObj || {},
          originCreatorOptions: _creatorData || {},
        };
        const userList = (_creatorData?.userList || []).map(
          (item: IOriginCreatorOption) => item.userId,
        );
        const queryType = activeKey || TABS_LIST.TODO_TABS_TYPE;
        if (isInit.current) {
          getSearchFormData({
            userList,
            queryType,
            searchFormObj: data,
          });
        } else {
          setInitialValues({ userList });
          // 改1
          setSearchCriteriaData({ userList, queryType, refreshUL: moment().valueOf() });
          setSearchFormData({ ...data });
        }
      }
    });
  }, [checkedDate, activeKey, flashKey]);

  // 获取筛选条件数据
  const getSearchFormData = async (obj?: any) => {
    const [res1, res2] = await Promise.all([getMarket(), getMaxElectricityGenerationRole()]);
    if (res1?.statusCode === HttpCode.SUCCESS && res2?.statusCode === HttpCode.SUCCESS) {
      const marketOptions = dealMarketOptions(res1.data || []);
      const dealElementResultData = getDealElementOptions(res2.data || []);

      const initialValues: IInitialValues = {
        marketList: (res1.data || []).map((item: IMarketOptions) => item.code),
        stationList: (dealElementResultData.value || []).map(
          (item: IDealElementOptions) => item.value,
        ),
        keyWords: '',
      };
      let data = {
        marketOptions,
        originDealElementOptions: res2.data,
        dealElementOptions: dealElementResultData?.value || [],
        dealElementModalOptions: dealElementResultData?.modalData || [],
        dealElementDataObj: dealElementResultData.dataObj,
      };
      const criteriaData: any = {
        marketList: (res1.data || []).map((item: IMarketOptions) => item.code),
        stationList: (dealElementResultData.value || []).map(
          (item: IDealElementOptions) => item.value,
        ),
        keyWords: '',
      };
      if (obj && isInit.current) {
        initialValues.userList = obj.userList;
        data = _.merge({}, data, obj.searchFormObj);
        criteriaData.userList = obj.userList;
        criteriaData.queryType = obj.queryType;
        isInit.current = false;
      }
      setInitialValues(initialValues);
      setSearchFormData(data);
      setSearchCriteriaData(criteriaData);
    } else {
      setError(res1?.statusCode !== HttpCode.SUCCESS ? res1?.message : res2?.message);
    }
  };

  // 获取月维度-清单
  const getMonthData = async () => {
    setComponentsLoadingStatus({
      calenderIsLoading: true,
    });
    const temp: any = {
      ...monthViewParams,
      marketList: null,
      stationList: null,
      userList: null,
      keyWords: null,
    };
    if (
      searchCriteriaData?.marketList?.length > 0 &&
      searchCriteriaData?.marketList?.length < searchFormData?.marketOptions?.length
    ) {
      temp.marketList = searchCriteriaData.marketList;
    }
    if (
      searchCriteriaData?.stationList?.length > 0 &&
      searchCriteriaData?.stationList?.length < searchFormData?.dealElementOptions?.length
    ) {
      temp.stationList = searchCriteriaData.stationList;
    }
    if (
      searchCriteriaData?.userList?.length > 0 &&
      searchCriteriaData?.userList?.length < searchFormData?.creatorOptions?.length
    ) {
      temp.userList = searchCriteriaData.userList;
    }
    if (searchCriteriaData?.keyWords) {
      temp.keyWords = searchCriteriaData.keyWords;
    }
    const res: any = await getMonthViewH(temp);
    if (res?.statusCode === HttpCode.SUCCESS) {
      setMonthData(mergeObjects(res?.data || []));
    }

    setComponentsLoadingStatus({
      calenderIsLoading: false,
    });
  };

  const mergeObjects = (obj: any) => {
    // 获取所有唯一日期键
    const allKeys = [...new Set([...Object.keys(obj)])];

    const result: any = {};

    allKeys.forEach((key) => {
      const val: any = obj[key] || { notice: false, todo: false, sequence: false };

      // 创建合并后的对象
      result[key] = {
        notice: val.notice,
        todo: val.todo,
        sequence: val.sequence,
      };
    });

    return result;
  };

  // 搜索列表
  const onSearch = async (params: IInitialValues, _flashKey?: string | number) => {
    if (!String(_flashKey)?.includes('edit')) {
      setComponentsLoadingStatus({
        listIsLoading: true,
      });
    }
    let res = null;
    res = await getTodoNoticeSequenceListH(params);
    if (res?.statusCode === HttpCode.SUCCESS) {
      const data = res?.data || [];
      const sortedData = data.sort(
        // @ts-ignore
        (a: any, b: any) => new Date(b.calendarDate) - new Date(a.calendarDate),
      );
      setListData(sortedData);
      setListIsError(false);
      setComponentsLoadingStatus({
        listIsLoading: false,
      });
    } else {
      setListData([]);
      setListIsError(true);
      setComponentsLoadingStatus({
        listIsLoading: false,
      });
    }
  };

  // 初始化函数
  // const fetchData = () => {
  //   getSearchFormData();
  // };

  // useEffect(() => {
  //   fetchData();
  // }, []);

  useEffect(() => {
    getMonthData();
  }, [monthViewParams, monthflashKey]);

  useEffect(() => {
    if (searchCriteriaData.dateList.length > 0 && searchCriteriaData.marketList.length > 0) {
      const params = {
        ...searchCriteriaData,
        /*  marketList:
          searchCriteriaData?.marketList?.length === searchFormData?.marketOptions.length
            ? []
            : searchCriteriaData?.marketList,
        stationList:
          searchCriteriaData?.stationList?.length === searchFormData?.dealElementOptions.length
            ? []
            : searchCriteriaData?.stationList, */
        marketList: searchCriteriaData?.marketList,
        stationList: searchCriteriaData?.stationList,
        // 改1
        userList: searchCriteriaData?.userList,
        // searchCriteriaData?.userList?.length === searchFormData?.creatorOptions.length
        //   ? []
        //   : searchCriteriaData?.userList,
      };
      onSearch(params, flashKey);
    }
  }, [
    searchCriteriaData.dateList,
    searchCriteriaData.marketList,
    // flashKey,
    searchCriteriaData.queryType,
    searchCriteriaData.refreshUL,
  ]);
  return error.length ? (
    <TRDefault type={'error'} message={error || '系统异常'} />
  ) : (
    <div className={styles.container}>
      <div className={styles.left}>
        <div className={styles.filter}>
          <div className={styles.title}>筛选条件</div>
          <SearchFrom
            initialValues={initialValues}
            searchCriteriaData={searchCriteriaData}
            setSelectFlashKey={setSelectFlashKey}
            searchFormData={searchFormData}
            setSearchCriteriaData={setSearchCriteriaData}
            setMonthflashKey={setMonthflashKey}
            setCheckedFlashKey={setCheckedFlashKey}
            buttonPermissions={buttonPermissions}
          />
        </div>
        <div className={styles.calender}>
          <Calender
            setCheckedDate={setCheckedDate}
            checkedDate={checkedDate}
            setSelectFlashKey={setSelectFlashKey}
            checkedFlashKey={checkedFlashKey}
            options={monthData}
            isLoading={componentsLoadingStatus.calenderIsLoading}
            setMonthViewParams={setMonthViewParams}
            setSearchCriteriaData={setSearchCriteriaData}
          />
        </div>
      </div>
      <div className={styles.right}>
        <div className={styles.list}>
          <List
            selectFlashKey={selectFlashKey}
            isError={listIsError}
            dataSource={listData}
            setFlashKey={setFlashKey}
            setComponentsLoadingStatus={setComponentsLoadingStatus}
            setActiveKey={setActiveKey}
            checkedDate={checkedDate}
            activeKey={activeKey}
            buttonPermissions={buttonPermissions}
            setMonthflashKey={setMonthflashKey}
            isLoading={componentsLoadingStatus.listIsLoading}
            setSearchCriteriaData={setSearchCriteriaData}
            searchFormData={searchFormData}
            getSearchFormData={getSearchFormData}
          />
        </div>
      </div>
    </div>
  );
};

export default connect(({ global }: any) => ({
  buttonPermissions: global.configure.buttonPermissions,
}))(DealCalenderRedesign);
